package com.jk1123.us.common.transfer;


import com.jk1123.us.common.transfer.radix.BigEndianRadix;
import com.jk1123.us.common.transfer.radix.Radix;

/**
 * @author huyoufu <https://github.com/huyoufu>
 * @TIME 2021-09-02 22:25
 * @description
 */
public class RadixTransfer {
    private Radix radix=new BigEndianRadix();
    public static final int MAX_LEN=8;
    public static final int RADIX_NUM=62;
    /**
     * 62^8次方 也就是最大值 20兆 这个数值太大了
     */
    public static final long MAX_NUM=218340105584896L;
    /**
     * 初始化了 最多8位的 62进制的值
     * 不考虑 超过8位以上的可能 因为是短地址服务
     * 8位绝对够用了 也不应该超过8位
     */
    private static final long[] RADIX_NUMS = {
            1L,
            62L,
            3844L,
            238328L,
            14776336L,
            916132832L,
            56800235584L,
            3521614606208L
    };

    public RadixTransfer() {
    }

    public RadixTransfer(Radix radix) {
        this.radix = radix;
    }


    public long string2num(String s){
        long result=0;
        int len=s.length();
        for (int i = 0; i < len; i++) {
            long tmp=RADIX_NUMS[len-i-1];
            result+=tmp*radix.char2int(s.charAt(i));
        }
        return result;
    }
    public String num2string(long num){
        if (num/RADIX_NUM==0){
            //说明数值小于62
            return String.valueOf(radix.num2char((int)num));
        }
        StringBuffer sb=new StringBuffer();

        while (num/RADIX_NUM!=0){
            long divisor=num/RADIX_NUM;
            long remainder= num%(long) RADIX_NUM;
            sb.append(radix.num2char((int)remainder) );
            num=divisor;
        }
        //最后一次的值
        long remainder= num%(long) RADIX_NUM;
        sb.append(radix.num2char((int)remainder) );



        return sb.reverse().toString();
    }

}
